<template>
  <div class="container">
    <div class="main">
      <el-table :data="filteredTableData" border class="eltable">
        <el-table-column fixed type="index" label="序号" width="80"></el-table-column>
        <el-table-column fixed prop="gdrw_state" label="工单状态" width="100">
          <template #default="{ row }">
            {{ dictionaryNames[row.gdrw_state] }}
          </template>
        </el-table-column>
        <el-table-column fixed prop="gdrw_yxj" label="优先级" width="80">
          <template #default="{ row }">
            {{ dictionaryNames[row.gdrw_yxj] }}
          </template>
        </el-table-column>
        <el-table-column fixed prop="gdrw_jd" label="工单进度" width="100">
          <template #default="{ row }">
            <div class="progress-bar">
              <div class="progress-fill" :style="{ width: `${row.gdrw_jd}%` }">
                {{ row.gdrw_jd }}%
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="gdrw_code" label="工单号" width="180"></el-table-column>
        <el-table-column prop="gdrw_fzr" label="负责人" width="180"></el-table-column>
        <el-table-column prop="gdrw_scwz" label="生产位置" width="180"></el-table-column>
        <el-table-column prop="cp_code" label="产品编码" width="180"></el-table-column>
        <el-table-column prop="cp_name" label="产品名称" width="180"></el-table-column>
        <el-table-column prop="cp_xh" label="产品型号" width="180"></el-table-column>
        <el-table-column prop="ks_name" label="客户名称" width="180"></el-table-column>
        <el-table-column prop="gdrw_jhsl" label="任务数量" width="180"></el-table-column>
        <el-table-column prop="gdrw_xqrq" label="交货日期" width="180">
          <template #default="{ row }">
            {{ formatDate(row.gdrw_xqrq) }}
          </template>
        </el-table-column>
        <el-table-column prop="gdrw_jhkgsj" label="计划开始时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.gdrw_jhkgsj) }}
          </template>
        </el-table-column>
        <el-table-column prop="gdrw_jhwgsj" label="计划完成时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.gdrw_jhwgsj) }}
          </template>
        </el-table-column>
        <el-table-column prop="gdrw_bz" label="备注" width="180"></el-table-column>
        <el-table-column prop="gd_tcsj" label="投产时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.gd_tcsj) }}
          </template>
        </el-table-column>
        <el-table-column prop="gdrw_sjkgsj" label="开工时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.gdrw_sjkgsj) }}
          </template>
        </el-table-column>
        <el-table-column prop="gdrw_sjwgsj" label="完成时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.gdrw_sjwgsj) }}
          </template>
        </el-table-column>
        <el-table-column prop="create_by" label="创建人" width="180"></el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="320">
          <template #default="{ row }">
            <el-button type="text" @click="Details(row)">详情</el-button>
            <el-button type="text" @click="Picking(row)">领料</el-button>
            <el-button type="text" @click="StartWork(row)">开工</el-button>
            <el-button type="text" @click="openDialog(row)">报工</el-button>
            <el-button type="text" @click="UpWork(row)">完工</el-button>
            <el-button type="text" @click="openDialog(row)">暂停</el-button>
            <el-button type="text" @click="openDialog(row)">恢复</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize"
        :total="totalItems" layout="total, prev, pager, next, jumper">
      </el-pagination>
    </div>
    <el-dialog title="工单任务详情" v-model="dialogVisibles" custom-class="plan-dialog"
      style="width: 900px; background-color: #fff; padding: 20px; box-shadow: 0 2px 15px rgba(0,0,0,0.15); border-radius: 30px;">
      <el-form :model="formData" label-width="100px" :rules="formRules" ref="formRef">
        <el-row>
          <el-col :span="8">
            <el-form-item label="生产工单号:">
              {{ formData.gdrw_code }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="优先级:">
              {{ dictionaryNames[formData.gdrw_yxj] }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="任务负责人:">
              {{ formData.gdrw_fzr }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="产品编码:">
              {{ formData.cp_code }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品名称:">
              {{ formData.cp_name }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品分类:">
              {{ dictionaryNames[formData.cp_fl] }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="产品型号:">
              {{ formData.cp_xh }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品品牌:">
              {{ formData.pp_name }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品类型:">
              {{ dictionaryNames[formData.cp_lx] }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="客户简称:">
              {{ formData.ks_name }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同编码:">
              {{ formData.ht_code }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="任务数量:">
              {{ formData.gdrw_jhsl }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="交货时间:">
              {{ formatDate(formData.gdrw_xqrq) }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划开始时间:">
              {{ formatDate(formData.gdrw_jhkgsj) }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划结束时间:">
              {{ formatDate(formData.gdrw_jhwgsj) }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="生产位置:">
              {{ formData.gdrw_scwz }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产班组:">
              {{ formData.gdrw_scbz }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="投产时间:">
              {{ formatDate(formData.gd_tcsj) }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="工艺路线:">
              {{ formData.gy_name }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产BOM:">
              {{ formData.bom_code }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="工单进度:">
              <div class="progress-bar">
                <div class="progress-fill" :style="{ width: `${formData.gdrw_jd}%` }">
                  {{ formData.gdrw_jd }}%
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="完成数量:">
              {{ formData.gdrw_sjscsl }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="完成时间:">
              {{ formatDate(formData.gdrw_sjwgsj) }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="工单状态:">
              {{ dictionaryNames[formData.gdrw_state] }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注:">
              {{ formData.gdrw_bz }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      ---------------------------------------------------------------------------------------------------------------------------------------------
      <p>生产资料:</p>
      <el-tabs v-model="activeTab" class="custom-tabs">
        <el-tab-pane label="生成BOM" name="bom"></el-tab-pane>
        <el-tab-pane label="产品属性" name="attributes"></el-tab-pane>
        <el-tab-pane label="工艺文件" name="process"></el-tab-pane>
        <el-tab-pane label="产品文档" name="documents"></el-tab-pane>
        <el-tab-pane label="产品图片" name="images"></el-tab-pane>
      </el-tabs>

      <!-- 根据 activeTab 的值决定显示哪个表格 -->
      <el-table v-if="activeTab === 'bom'" :data="bomData">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="wl_name" label="物料名称" />
        <el-table-column prop="wl_code" label="物料编码" />
        <el-table-column prop="wl_fl" label="物料分类">
          <template #default="{ row }">
            {{ dictionaryNames[row.wl_fl] }}
          </template>
        </el-table-column>
        <el-table-column prop="dw_name" label="物料单位" />
        <el-table-column prop="bomxq_sl" label="基本用料" width="100" />
      </el-table>

      <el-table v-if="activeTab === 'attributes'" :data="attributesData">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="attributeName" label="属性名称" />
        <el-table-column prop="attributeValue" label="属性值" width="200" />
      </el-table>

      <el-table v-if="activeTab === 'process'" :data="processData">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="processName" label="工序名称" />
        <el-table-column prop="processDetail" label="工艺文件" width="200" />
      </el-table>

      <el-table v-if="activeTab === 'documents'" :data="documentsData">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="documentName" label="文档名称" />
        <el-table-column prop="uploadDate" label="文档列表" width="200" />
      </el-table>

      <el-table v-if="activeTab === 'images'" :data="imagesData">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="imageName" label="产品图片" />
        <el-table-column prop="imageUrl" label="图片列表" width="300" />
      </el-table>

      <div style="margin-top: 20px;">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveForm">保存</el-button>
      </div>
    </el-dialog>
    <el-dialog v-model="isGYMTKVisible" title="选择工艺"
      style="height: 700px; width: 600px; background-color: #fff; padding: 20px; box-shadow: 0 2px 15px rgba(0,0,0,0.15); border-radius: 30px;">
      <GYMTK @selection-confirmed="handleSelectionConfirmed" @cancel-selection="handleCancelSelection"></GYMTK>
    </el-dialog>
    <el-dialog v-model="isWZMTKVisible" title="生产位置"
      style="height: 700px; width: 600px; background-color: #fff; padding: 20px; box-shadow: 0 2px 15px rgba(0,0,0,0.15); border-radius: 30px;">
      <DYMTK @selection-confirmed="handleSelectionConfirmeds" @cancel-selection="handleCancelSelections"></DYMTK>
    </el-dialog>

    <el-dialog v-model="isBZMTKVisible" title="生产班组"
      style="height: 700px; width: 600px; background-color: #fff; padding: 20px; box-shadow: 0 2px 15px rgba(0,0,0,0.15); border-radius: 30px;">
      <BZMTK @selection-confirmed="handleSelectionConfirmeds" @cancel-selection="handleCancelSelections"></BZMTK>
    </el-dialog>
  </div>
  <el-dialog v-model="lldialogVisibles" title="领料" width="500" align-center>
    <el-form-item label="请选择领料仓库">
      <el-select v-model="ck_code" placeholder="选择转出仓库" @change="handleLeaderChange">
        <el-option v-for="item in cktableData" :key="item.ck_code" :label="item.ck_name" :value="item.ck_code" />
      </el-select>
    </el-form-item>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="lldialogVisibles = false">取消</el-button>
        <el-button type="primary" @click="Pickingqr">确认</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="dialogVisible" title="报工" width="600" align-center>
    <template #footer>
      <div class="dialog-footer">
        <el-form :model="bgtableData" label-width="100px" :rules="formRules" ref="formRef">
          <el-row>
            <el-col :span="12">
              <el-form-item label="生产工单号:">
                {{ bgtableData.gdrw_code }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品编码:">
                {{ bgtableData.cp_code }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="产品名称:">
                {{ bgtableData.cp_name }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品型号:">
                {{ bgtableData.cp_xh }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="任务数量:">
                {{ bgtableData.gdrw_jhsl }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="已报工数量:">
                {{ bgtableData.gdrw_sjscsl }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="请选择工序">
                <el-select v-model="bgtableData.gx_code" placeholder="选择工序" style="width: 200px;"
                  @change="handleLeaderChange">
                  <el-option v-for="item in gxtableData" :key="item.gx_code" :label="item.gx_name"
                    :value="item.gx_code" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-button type="primary" @click="tj" style="float: right;">+添加</el-button>
        <el-table :data="bgxxtableData" border class="eltable" @selection-change="xghandleSelectionChange">
          <el-table-column label="报工人员">
            <template #default="{ row }">
              <el-select v-model="row.ry" placeholder="请选择" style="width: 100px" @change="handleLeaderChange">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="报工数量">
            <template #default="{ row }">
              <el-input v-model="row.sl" placeholder="请输入数量" />
            </template>
          </el-table-column>
        </el-table>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="bgqr">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import axios from 'axios';
import { ref, watchEffect, computed, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import DYMTK from '../MTK/DYMTK.vue';
import BZMTK from '../MTK/BZMTK.vue';
import GYMTK from '../MTK/GYMTK.vue';

export default {
  components: { DYMTK, BZMTK, GYMTK },
  setup() {
    const searchKey = ref('');
    const tableData = ref([]);
    const cktableData = ref([]);
    const bgtableData = ref([]);
    const bgxxtableData = ref([{ ry: '', sl: '' }]);
    const selectedFilter = ref('');
    const searchTable = ref('');
    const currentPage = ref(1);
    const pageSize = ref(10);
    const totalItems = ref(0);
    const dictionaryNames = ref({}); // 存储字典名称   

    const dialogVisible = ref(false);
    const dialogVisibles = ref(false);
    const lldialogVisibles = ref(false);
    const formData = ref({});
    const activeTab = ref('bom');
    const isGYMTKVisible = ref(false);
    const isBZMTKVisible = ref(false);
    const isWZMTKVisible = ref(false);
    const gxtableData = ref([]);
    //获取登录角色数据
    const uid = computed(() => {
      return sessionStorage.getItem('u');
    })
    let yhid = reactive({
      id: uid
    })
    let ck_code = ref('');
    const bomData = ref([]);
    const attributesData = ref([
      { id: 1, attributeName: '颜色', attributeValue: '黑色' },
      { id: 2, attributeName: '尺寸', attributeValue: '100x200' },
    ]);

    const processData = ref([
      { id: 1, processName: '切割', processDetail: '钢材切割' },
      { id: 2, processName: '焊接', processDetail: '钢材焊接' },
    ]);

    const documentsData = ref([
      { id: 1, documentName: '说明书', uploadDate: '2025-01-01' },
      { id: 2, documentName: '检测报告', uploadDate: '2025-02-01' },
    ]);

    const imagesData = ref([
      { id: 1, imageName: '产品图1', imageUrl: 'http://example.com/image1.jpg' },
      { id: 2, imageName: '产品图2', imageUrl: 'http://example.com/image2.jpg' },
    ]);
    const fetchData = async () => {
      try {
        const ckresponse = await axios.get('/api/Wbd_ck/Wbd_Ck');
        cktableData.value = ckresponse.data;
        const response = await axios.get('/api/Mes_gdrw/GetMes_gdrw');
        tableData.value = response.data;
        totalItems.value = response.data.length;
      } catch (error) {
        console.error('获取表格数据时出错:', error);
      }
    };
    const Details = async (row) => {
      bomData.value = []
      dialogVisibles.value = true;
      // 复制行数据到表单数据
      formData.value = { ...row };
      // 构建请求 URL
      const url = `/api/Mbd_BOMxq/GetBom?wl_code=${row.cp_code}`;
      // 发送请求获取 BOM 数据
      const response = await axios.get(url);
      console.log(response.data)
      // 将响应数据赋值给 bomData
      bomData.value = response.data;
      // 打开详情对话框
      dialogVisibles.value = true;
    };

    //报工
    const openDialog = async (row) => {
      console.log(row)
      if (row.gdrw_state == 53) {
        bgxxtableData.value = ([])
        gxtableData.value= ([])
        dialogVisible.value = true;
        bgtableData.value = row
        const bgresponse = await axios.get('/api/BG/GetBG?code=' + row.gdrw_code);
        console.log(bgresponse.data)
        let zon = ref(0)
        for (const team of bgresponse.data) {
          zon.value += team.bg_scsl
        }
        bgtableData.value.gdrw_sjscsl = zon.value
        const response = await axios.get('/api/GY_GX/GetMbd_GX?code=' + row.gy_code);
        for (const team of response.data) {
          const gxresponse = await axios.get('/api/MBD_GX/GetMbd_GXCode?code=' + team.gx_code);
          gxtableData.value.push(gxresponse.data)
        }
      } else {
        ElMessage.error('该任务未开工!');
      }

    };

    const handleCurrentChange = (page) => {
      currentPage.value = page;
    };

    const filteredTableData = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value;
      return tableData.value.slice(start, start + pageSize.value);
    });

    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}/${(date.getMonth() + 1).toString().padStart(2, '0')}/${date.getDate().toString().padStart(2, '0')}`;
    };

    const formatDictionaryName = async (dictionaryId) => {
      if (!dictionaryId) return '';
      if (dictionaryNames.value[dictionaryId]) {
        return dictionaryNames.value[dictionaryId];
      }
      try {
        const response = await axios.get(`/api/Dict/GetName?dictionary_id=${dictionaryId}`);
        dictionaryNames.value[dictionaryId] = response.data;
        return response.data;
      } catch (error) {
        console.error(`获取字典名称时出错: ${error.message}`);
        return '';
      }
    };
    // 关闭对话框
    const closeDialog = () => {
      dialogVisibles.value = false;
      formData.value = {};
      bomData.value = []
    };
    //显示工艺模态框
    const toggleGYMTK = () => {
      isGYMTKVisible.value = !isGYMTKVisible.value; // 切换显示状态  
    };
    //显示班组模态框
    const toggleBZMTK = () => {
      isBZMTKVisible.value = !isBZMTKVisible.value; // 切换显示状态  
    };
    //显示生产位置模态框
    const toggleWZMTK = () => {
      isWZMTKVisible.value = !isWZMTKVisible.value; // 切换显示状态  
    };
    // 监听表格数据变化，更新字典名称  
    watchEffect(() => {
      filteredTableData.value.forEach((row) => {
        if (row.gdrw_state) {
          formatDictionaryName(row.gdrw_state);
        }
        if (row.gdrw_yxj) {
          formatDictionaryName(row.gdrw_yxj);
        }
        if (row.cp_fl) {
          formatDictionaryName(row.cp_fl);
        }
        if (row.cp_lx) {
          formatDictionaryName(row.cp_lx);
        }
        if (row.wl_fl) {
          formatDictionaryName(row.cp_fl);
        }
        if (row.wl_lx) {
          formatDictionaryName(row.cp_lx);
        }
      });
    });
    //开工
    const StartWork = async (row) => {
      const response = await axios.get('/api/WMS_LLCK/GetWMS_LLCK?code=' + row.scgd_code)
      if (response.data.llck_zt == 2) {
        //判断该任务是否开工 如果为待投产的情况下就进行开工
        if (row.gdrw_state != 53) {
          ElMessageBox.confirm('确定开工吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(async () => {
              axios.put(`/api/Mes_gdrw/Updatesj?gdrw_code=${row.gdrw_code}&i=0&state=53&update_by=1`)
              return fetchData()
            })
            .catch(() => {
              ElMessage({
                type: 'info',
                message: '已取消开工'
              });
            });
        } else {
          ElMessage.error('该任务已投产不可操作!');
        }
      } else if (response.data.llck_zt == 1) {
        ElMessage.error('领料未出库')
      } else {
        ElMessage.error('未领料')
      }

    }
    let dq = ref()
    const Picking = async (row) => {
      const response = await axios.get('/api/WMS_LLCK/GetWMS_LLCK?code=' + row.scgd_code)
      if (response.data.llck_id == undefined) {
        lldialogVisibles.value = true
        dq.value = row
      } else {
        ElMessage.error("不能重复领料")
      }
    }
    //领料
    const Pickingqr = async () => {
      //构建请求 URL
      const url = `/api/Mbd_BOMxq/GetBom?wl_code=${dq.value.cp_code}`;
      // 发送请求获取 BOM 数据
      const wlresponse = await axios.get(url);
      const sf = ref(false);
      try {
        for (const team of wlresponse.data) {
          const ckresponse = await axios.get('/api/WMS_KC/GetWMS_KCWL?ck_code=' + ck_code.value + '&wl_code=' + team.wl_code)
          if (ckresponse.data.length > 0) {
            const zon = ref(0);
            for (const team of ckresponse.data) {
              zon.value += team.kc_sl - team.kc_jhsl;
            }
            if (dq.value.gdrw_jhsl * team.bomxq_sl > zon) {
              ElMessage.error("该仓库数量不够")
              sf.value = false
              return;
            } else {
              sf.value = true
            }
          } else {
            ElMessage.error('这个仓库没有该物料')
            return
          }
        }
      } catch (error) {
        console.error('Error fetching product details:', error);
      }
      if (sf.value) {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1并补零
        const day = String(now.getDate()).padStart(2, '0'); // 补零

        // 生成四位随机数
        const randomNumber = Math.floor(1000 + Math.random() * 9000); // 生成1000到9999之间的随机数

        // 拼接时间字符串和随机数
        const formattedTime = `${year}${month}${day}`;
        let id = `llck${formattedTime}${randomNumber}`
        try {
          const tjresponse = await axios.post('/api/WMS_LLCK/Addllck', {
            llck_code: id,
            llck_lx: "领料出库",
            llck_jhllsj: dq.value.gdrw_jhkgsj,
            llck_gdh: dq.value.scgd_code,
            llck_bz: dq.value.gdrw_bz,
            create_by: yhid.id
          });
          if (tjresponse.data) {
            // 构建请求 URL
            // const url = `/api/Mbd_BOMxq/GetBom?wl_code=${dq.value.cp_code}`;
            // // 发送请求获取 BOM 数据
            // const response = await axios.get(url);
            // console.log(response.data);
            const sf = ref(false);
            let dw = ref(1)
            for (const team of wlresponse.data) {
              let sl = dq.value.gdrw_jhsl * team.bomxq_sl
              const response1 = await axios.post('/api/WMS_LLCKXX/Addllckxx', {
                wl_code: team.wl_code,
                llckxx_wlmc: team.wl_name,
                llckxx_wlfl: team.wl_fl,
                llckxx_ggxh: team.wl_xh,
                llckxx_ckck: ck_code.value,
                llckxx_wldw: dw.value,
                llckxx_cksl: sl,
                llck_code: id,
                ck_name: ''
              });
              if (response1.data) {
                const response1 = await axios.get('/api/WMS_KC/GetWMS_KCWL?ck_code='+ck_code.value+'&wl_code='+team.wl_code)
                const response = await axios.put('/api/WMS_KC/UpdateWMS_KC?id='+response1.data[0].kc_id+'&sl='+sl)
                sf.value = true
              } else {
                sf.value = false
                return;
              }
            }
            if (sf.value) {
              ElMessage.success('成功')
              fetchData()
            }
          }
        } catch (error) {
          console.error('Error fetching product details:', error);
        }
      } else {
        ElMessage.error('无法添加')
      }

    }
    const BaoGong = (row) => {
      ElMessageBox.confirm('确定报工吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {

        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消报工'
          });
        });
    }
    //完工
    const UpWork = (row) => {
      //判断该任务是否完工 如果为生产中的情况下就可以进行完工
      if (row.gdrw_state == 53) {
        ElMessageBox.confirm('确定完工吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1并补零
            const day = String(now.getDate()).padStart(2, '0'); // 补零

            // 生成四位随机数
            const randomNumber = Math.floor(1000 + Math.random() * 9000); // 生成1000到9999之间的随机数

            // 拼接时间字符串和随机数
            const formattedTime = `${year}${month}${day}`;
            let id = `cp${formattedTime}${randomNumber}`
            const rkResponse = await axios.post('/api/WMS_CCPRK/AddCCPRK', {
              cprk_code: id,
              cprk_lx: '成品入库',
              cprk_gdh: row.scgd_code,
              cprk_bz: row.gdrw_scbz,
              create_by: yhid.id,
            });
            if (rkResponse.data) {
              const rkxxResponse = await axios.post('/api/WMS_CCPRKXX/AddCCPRKXX', {
                cp_code: row.cp_code,
                cprkxx_cpmc: row.cp_name,
                cprkxx_cpfl: row.cp_fl,
                cprkxx_cpdw: row.dw_code,
                cprkxx_rksl: row.gdrw_jhsl,
                cprk_code: id,
              });
              if (rkxxResponse.data) {
                const Response = await axios.put('/api/Mes_gdrw/WanGong?code=' + row.gdrw_code + '&shu=' + row.gdrw_jhsl)
                if (Response.data) {
                  const Response = await axios.put('/api/Mes_SCGD/UpdateScgdJD?zt=52&sl=' + row.gdrw_jhsl + '&jd=100&code=' + row.scgd_code)
                  if (Response.data) {
                    const gdResponse = await axios.get('/api/Mes_SCGD/GetGD?code=' + row.scgd_code)
                    const gdsResponse = await axios.get('/api/Mes_SCGD/GetMes_scjhcode?scjh_code=' + gdResponse.data.scjh_code)
                    let jd = Math.floor(1 / gdsResponse.data.length * 100)
                    const Response = await axios.put('/api/Mes_scjh/UpdateMesScjhJD?jd=' + jd + '&code=' + gdResponse.data.scjh_code)
                    if (Response.data) {
                      let sf = ref(0);
                      for (const team of gdsResponse.data) {
                        if (team.gd_state = 52) {
                          sf.value++
                        }
                      }
                      if (sf == gdsResponse.data.length) {
                        const Response = await axios.put('/api/Mes_scjh/UpdateStatus?scdd_code=0&state=52&update_by=' + yhid.id + '&scjh_code=' + gdResponse.data.scjh_code)
                        if (Response.data) {
                          const Response = await axios.put('/api/Mes_scjh/UpdateMesScjhJD?jd=100&code=' + gdResponse.data.scjh_code)
                          if (Response.data) {
                            const jhResponse = await axios.get('/api/Mes_scjh/GetJH?code=' + gdResponse.data.scjh_code)
                            const jhsResponse = await axios.get('/api/Mes_scjh/GetJHS?code=' + jhResponse.data.scdd_code)
                            let jd = Math.floor(1 / jhsResponse.data.length * 100)
                            const Response = await axios.put('/api/Mes_SCDD/UpdateMesSCDDJD?jd=' + jd + '&code=' + jhResponse.data.scdd_code)
                            if (Response.data) {
                              for (const team of jhsResponse.data) {
                                let sf = ref(0);
                                if (team.scjh_state = 52) {
                                  sf.value++
                                }
                              }
                              console.log(sf)
                              console.log(jhsResponse.data.length)
                              if (sf == jhsResponse.data.length) {
                                const Response = await axios.put('/api/Mes_scjh/UpdateMesSCDDJD?jd=100&code=' + jhResponse.data.scdd_code)
                                if (Response.data) {
                                  const Response = await axios.put('/api/Mes_SCDD/UpdateStatus?code=' + jhResponse.data.scdd_code + '&state=52&update_by=' + yhid.id)
                                  if (Response.data) {
                                    ElMessage.success('成功')
                                    fetchData()
                                  }
                                }
                                ElMessage.success('成功')
                                fetchData()
                              } else {
                                ElMessage.success('成功')
                                fetchData()
                              }
                            }

                          }
                        }
                      } else {
                        const jhResponse = await axios.get('/api/Mes_scjh/GetJH?code=' + gdResponse.data.scjh_code)
                        const jhsResponse = await axios.get('/api/Mes_scjh/GetJHS?code=' + jhResponse.data.scdd_code)
                        let jd = Math.floor(1 / gdsResponse.data.length / jhsResponse.data.length * 100)
                        const Response = await axios.put('/api/Mes_SCDD/UpdateMesSCDDJD?jd=' + jd + '&code=' + jhResponse.data.scdd_code)
                        if (Response.data) {
                          ElMessage.success('成功')
                          fetchData()
                        }

                      }
                    }
                  }
                }
              } else {
                ElMessage.error('失败')
              }
            }
            return axios.put(`/api/Mes_gdrw/Updatesj?gdrw_code=${row.gdrw_code}&i=1&state=52&update_by=1`)
          })
          .catch(() => {
            ElMessage({
              type: 'info',
              message: '已取消完工'
            });
          });
      } else {
        ElMessage.error('该任务未投产不可操作!');
      }
    }
    fetchData();
    function tj() {
      bgxxtableData.value.push([{ ry: '', sl: '' }])
    }
    async function bgqr() {
      console.log(bgtableData.value)
      let sf = ref(false)
      for (const team of bgxxtableData.value) {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1并补零
        const day = String(now.getDate()).padStart(2, '0'); // 补零

        // 生成四位随机数
        const randomNumber = Math.floor(1000 + Math.random() * 9000); // 生成1000到9999之间的随机数

        // 拼接时间字符串和随机数
        const formattedTime = `${year}${month}${day}`;
        let id = `bg${formattedTime}${randomNumber}`
        const response = await axios.post('/api/BG/PostBG', {
          bg_code: id,
          gx_code: bgtableData.value.gx_code,
          scgd_code: bgtableData.value.gdrw_code,
          bg_by: team.ry,
          bg_scsl: team.sl
        })
        if (response.data) {
          sf.value = true
        } else {
          sf.value = false
          return
        }
      }
      if (sf) {
        ElMessage.success('成功')
        fetchData()
        dialogVisible.value = false
      } else {
        ElMessage.error('失败')
      }
    }
    return {
      searchKey,
      tableData,
      selectedFilter,
      searchTable,
      currentPage,
      pageSize,
      totalItems,
      openDialog,
      handleCurrentChange,
      formatDate,
      formatDictionaryName,
      dictionaryNames,
      filteredTableData,
      Details,
      dialogVisibles,
      formData,
      activeTab,
      bomData,
      attributesData,
      processData,
      documentsData,
      imagesData,
      closeDialog,
      toggleGYMTK,
      toggleBZMTK,
      toggleWZMTK,
      isGYMTKVisible,
      isBZMTKVisible,
      isWZMTKVisible,
      StartWork,
      UpWork,
      Picking,
      cktableData,
      lldialogVisibles,
      ck_code,
      Pickingqr,
      dialogVisible,
      bgtableData,
      gxtableData,
      bgxxtableData,
      options: [{
        value: 1,
        label: '张三'
      }, {
        value: 2,
        label: '李四'
      }, {
        value: 3,
        label: '王五'
      }],
      tj,
      bgqr,
      BaoGong
    };
  },
};
</script>

<style>
.container {
  display: flex;
  gap: 20px;
  height: 95%;
}

.main {
  width: 80%;
  flex: 1;
  height: 100%;
}

.header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.eltable {
  height: 95%;
}

.progress-bar {
  width: 100%;
  height: 20px;
  background-color: #e0e0e0;
  border-radius: 15px;
  overflow: hidden;
  position: relative;
}

.progress-fill {
  height: 100%;
  background-color: #409eff;
  border-radius: 15px 0 0 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: rgb(0, 0, 0);
  font-weight: bold;
  transition: width 0.3s;
}

.custom-tabs .el-tabs__item {
  border-radius: 12px 12px 0 0;
}

.custom-tabs .el-tabs__item.is-active {
  background-color: #409eff;
  /* 活动选项卡的背景色 */
  color: white;
  /* 活动选项卡的字体颜色 */
}

.custom-tabs .el-tabs__item.is-inactive {
  background-color: #f5f7fa;
  /* 非活动选项卡的背景色 */
  color: #606266;
  /* 非活动选项卡的字体颜色 */
}

.custom-tabs .el-tabs__nav {
  margin-bottom: -1px;
  /* 使选项卡与下方内容相连 */
}

.el-table {
  margin-top: 20px;
}
</style>